<%--
  Created by IntelliJ IDEA.
  User: nick
  Date: 8/08/12
  Time: 2:37 PM
  To change this template use File | Settings | File Templates.
--%>
<%@ page import="grails.converters.JSON" contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Tree for ${treeInstance.name}</title>
    <meta name="layout" content="main" />
    <link rel="stylesheet" href="${resource(dir: 'css', file: 'PhyloJive.css')}" type="text/css" media="screen" />
    <link rel="stylesheet" href="${resource(dir: 'css/colorbox', file: 'colorbox.css')}" type="text/css" media="screen" />
    <link rel="stylesheet" href="${resource(dir: 'css', file: 'jquery.contextMenu.css')}" type="text/css" media="screen" />

    <script type="text/javascript" src="${resource(dir: 'js', file: 'jit.js')}"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    %{--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.js"></script>--}%
    <script type="text/javascript" src="${resource(dir: 'js', file: 'jquery-ui-1.8.16.custom.min.js')}"></script>
    <script type="text/javascript" src="http://raw.github.com/jackmoore/colorbox/v1.3.16/colorbox/jquery.colorbox-min.js"></script>
    <script type="text/javascript" src="${resource(dir: 'js', file: 'jquery.contextMenu.js')}"></script>
    <script type="text/javascript" src="http://www.jsphylosvg.com/js/jsphylosvg-min.js"></script>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
    <script type="text/javascript" src="${resource(dir: 'js', file: 'PhylogenyExplorer.js')}"></script>
    <!--[if IE]><script language="javascript" type="text/javascript" src="${resource(dir: 'js', file: 'excanvas.js')}"></script><![endif]-->
    <script type="text/javascript">
        var tree = "${treeInstance.newick}";
        var characters = jQuery.parseJSON( '${treeInstance.characters?:""}' );
        var IlDataset = "${treeInstance.identifyLifeDataset}";

        $(document).ready(function() {
            init_phylojive(tree, characters);
        });

        function init_phylojive(tree, characters) {
            //console.log("getkey", getKey(characters), getKey(characters[getKey(characters)]));
            phylogenyExplorer_init({
                width: 900,
                height: 500,
                tree: tree,
                branchMultiplier: 2,
                character: characters,
                toolWidget: "accordion", // tabs || accordion
                codeBase: "${resource(dir: 'images')}",
                presentClade: function(clade) {
                    var tmpl = st.config.tmpl, nodeList = [], node, html, split;
                    for (var i = 0;
                         ((i < clade.length) & (i < 30)); i++) {
                        node = {}
                        node.name = clade[i].name;
                        node.plus = clade[i].name.replace(/\s+/g, '+');
                        split = node.name.split(/\s+/);
                        if (split.length > 1) {
                            node.genus = split[0];
                            node.species = split[1];
                        } else {
                            node.species = split[0];
                        }
                        node.rel = node.species + '' + i;
                        node.index = i;
                        nodeList.push(node);
                    }
                    if (tmpl) {
                        tmpl = _.template(tmpl);
                        html = tmpl({
                            nodeList: nodeList
                        });
                    } else {

                    }
                    return html;

                },
                //presentClade
                tmpl: '${treeInstance.popupTemplate}'
            });
        } // end init_phylojive

        function objLength(obj) {
            var L=0;
            $.each(obj, function(i, elem) {
                L++;
            });
            return L;
        }

        function remoteLoadCharacters(url, characters, dataset) {
            //console.log("remoteLoadCharacters", url, characters, dataset);
            var nodes = [];
            var root = st.graph.getNode(st.root);
            var allChars = jQuery.extend(true, {}, characters) || {}; // copy not reference it
            // iterate over tree and extract names
            root.eachSubgraph(function (node) {
                if (node.name) {
                    var sciName = node.name.replace(/\s+\d+/,""); // strip off year strings
                    nodes.push(sciName);
                    // create stub for all names with no existing props
                    if (!allChars[node.name]) {
                        allChars[node.name] = {};
                    }
                }
            });
            var joinedNames = nodes.join(";").replace(/\s+/g, "+");
            url += "?names=" + joinedNames + "&dataset=" + dataset;
            //console.log("joinedNames", joinedNames);
            //console.log("url", url);
            jQuery.getJSON(url, function(data) {
                var propObj = {}, maxProps = 0, oldChars = {}, charsFound = false;
                jQuery.each(data, function(key, el) {
                    //oldChars[key] = jQuery.extend(true, {}, allChars[key] ); //copy it
                    //console.log("key:", key, el, oldChars[key], allChars[key]);
                    jQuery.extend(allChars[key], el); // merge props
                    if (el) charsFound = true;
                    // (do once) build a list of all (merged) properties
                    if (objLength(propObj) <= 0 && allChars[key]) {
                        maxProps = objLength(allChars[key]);
                        jQuery.each(el, function(k, v) {
                            //propList.push(k);
                            propObj[k] = [];
                        });

                    }
//                    if (newChars[key]) {
//                        jQuery.extend(true, newChars[key], el); // merge props
//                    } else {
//                        newChars[key] = el;
//                    }
                });
                // normalise the properties for all taxa
                jQuery.each(allChars, function(key, el) {
                    //console.log("newChars check",key,el,objLength(el),maxProps);
                    //console.log("char's length", el.length, maxProps);
                    if (objLength(el) < maxProps) {
                        //console.log("mismatch", key);
                        jQuery.extend(true, el, propObj);
                    }
                });
                // determine the first character for first taxa
                var firstChar;
                for (var key in allChars) {
                    if (allChars[key]) {
                        firstChar = getKey(allChars[key]);
                        break;
                    }
                }

                //console.log("allChars", allChars, getKey(allChars), firstChar, characters);
                //console.log("st", st);
                //st.compute();
                //st.firstCharacter = false; //firstChar;
                st.config.initCharacter = false;
                st.character = allChars || {}; // st.characterList ???
                //console.log("st 2", st);
                if (charsFound && st.character) {
                    html = st.colorCharacter() || '';
                    jQuery('#legendBody').html(html);
                    //legendElem.style.display = 'inline';
                    jQuery('#legend').show();
                    //st.findAllCharTypes(st.graph.getNode(st.root));
                    updateCharacter(st.characterList);
                    //console.log("triggering navigate:", window.location.hash.slice(1));
                    var hashString = window.location.hash.slice(1);
                    // we need the URL to change in order to get navigate to trigger -> toggle first hash value
                    var fiddleHash1 = (hashString.indexOf("characters") > -1) ? "character" : "characters";
                    var fiddleHash2 = (hashString.indexOf("characters") > -1) ? "characters" : "character";
                    window.AppRouter.navigate(hashString.replace(fiddleHash2, fiddleHash1),{trigger: true, replace: true});
                    st.fitScreen();
                    alert("characters were loaded successfully");
                } else {
                    alert("No characters were found for this tree");
                    jQuery('#legend').hide();
                }
            }).error(function(jqXHR, textStatus, errorThrown){ alert("getJSON Error: " + textStatus);});
        }

        function getKey(data) {
            for (var prop in data)
                return prop;
        }

    </script>
</head>
<body>
<section class="container-fluid">
    <div class="row-fluid">
        <div id="infovis"></div>
    </div>
</section>
</body>
</html>